"""CopyRight(C) From WangShiheng"""
# Author: WangShiheng
# Package
import inspect
import time

from util.base.LOGGER import LOGGER, Logger


def retry(cs=-1, timeout=100, catch_exception=True):
    def wrapper(func, *args, **kwargs):
        start_time = time.time()
        while (not (cs == 0)) and int(time.time() - start_time) // 100 <= timeout:
            try:
                func(*args, **kwargs)
            except Exception:
                print("It's error in {}. retry in {} time(s)".format(inspect.stack()[0][3], cs))
            finally:
                cs -= 1

    return wrapper


def time_test(cs=1, is_print=True, LOG: Logger = LOGGER()):
    def wrapper(func):
        def _wrapper(*args, **kwargs):
            times = []
            error_times = 0
            for i in range(cs):
                LOG.info(f"Test Func {i + 1}/{cs}")
                # try:
                st = time.time()
                func(*args, **kwargs)
                et = time.time()

                times.append(et - st)

                # except KeyboardInterrupt:
                #     break
                # except Exception as e:
                #     print("on {} error".format(i))
                #     error_times += 1

            avg = sum(times) / len(times)

            string = 'cs:{}, avg:{}, error:{}c'.format(cs, avg, error_times)
            if is_print:
                print(string)
            return string

        _wrapper()
        return _wrapper

    return wrapper
